package org.io4j.resource;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;

import org.io4j.InputOutputException;
import org.io4j.util.Argument;

/**
 * A {@code Resource} that can be found on the Internet.
 * 
 */
public class UrlResource extends BaseResource {

	private final URL url;

	/**
	 * Constructs a resource from {@code URL} location.
	 * 
	 * @throws IllegalArgumentException
	 *            if URL is {@code null}
	 */
	public UrlResource(URL url) {
		Argument.isNotNull(url, "URL is null");
		this.url = url;
	}

	/**
	 * Constructs a resource from {@code URI} location.
	 * 
	 * @throws IllegalArgumentException
	 *            if URI is {@code null}, or has missing or invalid scheme
	 */
	public UrlResource(URI uri) {
		Argument.isNotNull(uri, "URI is null");
		try {
			this.url = uri.toURL();
		} catch (MalformedURLException e) {
			throw new IllegalArgumentException("Scheme is missing or invalid in '" + uri.toString()
					+ "'", e);
		}
	}

	public InputStream openInputStream() {
		try {
			URLConnection connection = url.openConnection();
			connection.setUseCaches(false);
			return connection.getInputStream();
		} catch (IOException e) {
			throw new InputOutputException("Could not open '" + url + "' for reading", e);
		}
	}

	public URL getUrl() {
		return url;
	}

	public String getName() {
		return url.getPath();
	}
}
